/*
 * CartDocument.java
 * 
 * Created by demory on Mar 1, 2010, 8:45:04 PM
 * 
 * Copyright 2008 David D. Emory
 * 
 * This file is part of Five Points. See <http://www.fpdev.org> for
 * additional information regarding the project.
 * 
 * Five Points is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * Five Points is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with Five Points.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.fpdev.apps.cart;

import java.io.File;
import java.io.FileWriter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.fpdev.apps.cart.network.CartNetwork;
import org.fpdev.apps.cart.network.LineStyles;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 *
 * @author demory
 */
public class CartDocument {

  private CartNetwork network_;
  private LineStyles styles_;

  private File activeFile_;

  public CartDocument() {
    network_ = new CartNetwork(this);
    styles_ = new LineStyles();
  }

  public CartNetwork getNetwork() {
    return network_;
  }

  public LineStyles getStyles() {
    return styles_;
  }

  public boolean hasActiveFile() {
    return activeFile_ != null;
  }

  public File getActiveFile() {
    return activeFile_;
  }

  public void readXMLFile(File file) {
    System.out.println("Loading transit data from XML file");

    try {
      DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
      Document doc = docBuilder.parse(file);
      NodeList docNodes = doc.getChildNodes();
      Node thisNode = docNodes.item(0);
      if (!thisNode.getNodeName().equals("cartographer")) {
        System.out.println("Not a valid Cartographer data file");
        return;
      }

      styles_.readFromXML(thisNode);
      network_.readFromXML(thisNode);
      
      activeFile_ = file;
      //System.out.println("af="+activeFile_);
    } catch(Exception e) {
      e.printStackTrace();
    }
  }

  public void writeXMLFile() {
    if(activeFile_ == null) return;
    writeXMLFile(activeFile_);
  }

  public void writeXMLFile(File file) {

    try {
      FileWriter writer = new FileWriter(file);
      writer.write("<?xml version=\"1.0\"?>\n");
      writer.write("<cartographer>\n");
      writer.write(network_.getXML("  "));
      writer.write(styles_.getXML("  "));
      writer.write("</cartographer>\n");
      writer.close();
      activeFile_ = file;

    } catch(Exception e) {
      e.printStackTrace();
    }
  }
}
